package pers.qianyu.diytomcat.classloader;

import cn.hutool.core.io.*;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * @author mizzle rain
 * @date 2021-01-09 16:22
 */
public class WebappClassLoader extends URLClassLoader {
    public WebappClassLoader(String docBase, ClassLoader commonClassLoader) {
        super(new URL[]{}, commonClassLoader);
        try {
            File webInfFolder = FileUtil.file(docBase, "WEB-INF");
            File libFolder = FileUtil.file(webInfFolder, "lib");
            File classesFolder = FileUtil.file(webInfFolder, "classes");
            this.addURL(new URL("file:" + classesFolder.getAbsolutePath() + "/"));
            if (libFolder.exists() && libFolder.isDirectory()) {
                List<File> files = FileUtil.loopFiles(libFolder);
                for (File file : files) {
                    if (file.getName().endsWith(".jar")) {
                        this.addURL(new URL("file:" + file.getAbsolutePath()));
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        try {
            close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
